const mutations = {
  // 创建一个 add 方法通过 payload 将数据添加进 cart 数组中
  add(state, payload) {
    // 创建一个常量来保存id相同的商品
    // 判断当前选购商品在购物车中是否已存在
    // 如果已存在,则叠加数量，不存在，添加到数组中
    const has = state.cart.some(prod => prod.id === payload.id)
    if (has) {
      state.cart = state.cart.map(prod => {
        const copy = { ...prod }
        if (copy.id === payload.id) {
          copy.amount += payload.amount
        }
        return copy
      })
    } else {
      const prod = {
        ...payload,
        checked: true, // 选中状态
      }
      state.cart.push(prod)
    }
  },
  // 删除商品数据
  remove(state, payload) {
    state.cart = state.cart.filter(prod => prod.id !== payload)
  },
  // 商品数据的添加修改
  changeAmount(state, payload) {
    state.cart = state.cart.map(prod => {
      const copy = { ...prod }
      if (prod.id === payload.id) {
        copy.amount = payload.value
      }
      return copy
    })
  },
  // 修改选中状态
  toggleChecked(state, payload) {
    state.cart = state.cart.map(prod => {
      const copy = { ...prod }
      if (copy.id === payload) {
        copy.checked = !copy.checked
      }
      return copy
    })
  },
  // 全选/取消全选
  // payload 表示是否已全选
  toggleCheckedAll(state, payload) {
    state.cart = state.cart.map(prod => {
      const copy = { ...prod }
      copy.checked = !payload
      return copy
    })
  },
}

export default mutations
